package 数据结构上

import scala.collection.mutable

object MapDemo01 {

  def main(args: Array[String]): Unit = {
    /*scala中的Map分为可变(mutable)he不可变(immutable)*/
    //默认创建 map 时不可变的,构建如下,构成的每个元素是元组类型,这是 tuple2类型
    val map = Map("Alice" -> 10, "Tom" -> 20, "Tony" -> "北京")

    /*创建可变的map*/
    val map2 = mutable.Map("Alice" -> 10, "Tom" -> 20, "Tony" -> "北京")
    print(map2)

    /*创建空的map*/
    val map3 = new scala.collection.mutable.HashMap[String, Int]
    print(map3)

    /*对偶元组*/
    val map4 = mutable.Map(("tom", 1), ("sam", 2), ("sun", 3))
    print(map4)

    /**
     * 取出数据
     */
    /*key如果不存在会抛出异常*/
    val i = map4("tom")
    println(i)

    if (map4.contains("tom")) println(map4("tom"))

    val maybeInt = map4.get("san")
    //    val value = maybeInt.get

    /**
     * 修改,添加,删除
     */
    /*增加*/
    map4("aa") = 5;
    map4 += ("bbb" -> 7)
    println(map4)
    /*修改*/
    map4("aa") = 6
    println(map4)
    /*删除*/
    map4.remove("aa")
    map4 -= ("b")

    /**
     * map的遍历
     *
     */
    val map5 = mutable.Map("A" -> "北京", "B" -> "上海", "C" -> "广州")
    for ((k, v) <- map5) {
      println(k + ":" + v)
    }
    for (v <- map5.keys) {
      println("k:" + v)
    }
    for (v <- map5.values) {
      println("v:" + v)
    }
    /*返回的是元组,Tuple2类型*/
    for (v <- map5) {
      println(v)
    }


  }
}
